package com.silence.qhyh.webpro.app.widget.verificationcode;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.orhanobut.logger.Logger;
import com.silence.qhyh.webpro.mvp.ui.activity.login.VerificationCodeActivity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author silence
 * 自动填写短信验证码
 */
public class MessageContentObserver extends ContentObserver {

    private Context mContext;
    private Handler mHandler;

    public MessageContentObserver(Context context, Handler handler) {
        super(handler);
        mContext = context;
        mHandler = handler;
    }

    /**
     * 回调函数, 当监听的Uri发生改变时，会回调该方法
     * 需要注意的是当收到短信的时候会回调两次
     * 收到短信一般来说都是执行了两次onchange方法.第一次一般都是raw的这个.
     * 虽然收到了短信.但是短信并没有写入到收件箱里
     */
    @Override
    public void onChange(boolean selfChange, Uri uri) {
        if (uri.toString().equals("content://sms/raw")) {
            return;
        }
        Cursor c = null;
        // 读取收件箱中含有某关键词的短信
        ContentResolver contentResolver = mContext.getContentResolver();
        c = contentResolver.query(Uri.parse("content://sms/inbox"), new String[]{
                        "_id", "address", "body", "read"}, "body like ? and read=?",
                new String[]{"%企惠壹号%", "0"}, "date desc");
        if (c != null && c.getColumnCount() > 0) {
            if (c.moveToFirst()) {
                String address = c.getString(c.getColumnIndex("address"));//发送方号码
                String body = c.getString(c.getColumnIndex("body")); // 短信内容
                Logger.e("地址为： " + address);
                if (address.contains("1069")) {
                    if (!body.startsWith("【企惠壹号】")) {
                        return;
                    }
                    Pattern pattern = Pattern.compile("(\\d{4})");//正则表达式匹配验证码
                    Matcher matcher = pattern.matcher(body);
                    if (matcher.find()) {
                        String code = matcher.group(0);
                        Message msg = Message.obtain();
                        msg.what = VerificationCodeActivity.MSG_RECEIVE_CODE;
                        Bundle bundle = new Bundle();
                        bundle.putString("code", code);
                        msg.setData(bundle);
                        mHandler.sendMessage(msg);
                    }
                    return;
                }
            }
            c.close();
        }
    }
}